<template>
	<view class="container">
		<scroll-view class="table" scroll-x="true">
			<view class="table-header">
				<text class="table-cell">房间号</text>
				<text class="table-cell">充值金额(元)</text>

				<text class="table-cell">充值时间</text>
				<text class="table-cell">领取状态</text>
			</view>
			<view class="table-row" v-for="(item, index) in data1" :key="index">
				<text class="table-cell">{{ item.SS_MC }}</text>
				<text class="table-cell">{{ item.money }}</text>
				<text class="table-cell">{{ convertTime (item.updatedAt)}}</text>
				<text class="table-cell">{{ getStatusText(item.qc_state) }}</text>
			</view>
		</scroll-view>
		<view class="bottom-button" @click="reback">一键领取</view>
	</view>
	</view>
</template>

<script>
	import SearchDateRange from '@/component/SearchDateRange.vue';
	import {
		ajax
	} from '../../utils/request.js';

	export default {
		components: {
			SearchDateRange
		},
		data() {
			return {
				data1: [],
				data: [],
				formattedTime: '',
				searchValue: '',
				currentPage: 1,
				itemsPerPage: 10,
				start: '',
				end: '',
				signal: '', //蓝牙信号
				upsuccess: true,

				UUID: '',
				device: {}, //设备信息
				title: '', //加载标题
				serviceu: "", // 服务地址
				txdu: "", // 发送数据
				rxdu: "", // 接收数据
				serviceId: "", //服务id
				characteristicId: "", //特征值id
				hex: "", //蓝牙返回的数据
			};
		},
		computed: {
			totalPages() {
				return Math.ceil(this.data.length / this.itemsPerPage);
			},
			paginatedData() {
				const start = (this.currentPage - 1) * this.itemsPerPage;
				const end = start + this.itemsPerPage;
				return this.data.slice(start, end);
			}
		},
		onShow() {
			this.start = null; // 初始化时间参数为 null
			this.end = null;
			this.fetchFormData();
			//获取设备信息
			this.device = uni.getStorageSync("device");
			//判断设备
			if (uni.getSystemInfoSync().platform === 'ios') {
				console.log("ios用户");
				this.title = "正在搜索设备";
				uni.showLoading({
					title: this.title,
					mask: true
				});
				// 获取设备ID
				this.getBluetoothDeviceIdByName(this.device.BluetoothName)
					.then(deviceId => {
						console.log('找到设备ID:', deviceId);
						this.UUID = deviceId;
						console.log('uuid', this.UUID)
						this.title = "正在连接蓝牙..."
						// 开始连接蓝牙
						this.connect();
					})
					.catch(error => {
						console.error('错误:', error.message);
					});
			} else {
				this.UUID = this.device.UUID;
				console.log('uuid', this.UUID)
				this.title = "正在连接蓝牙..."
				uni.showLoading({
					title: this.title,
					mask: true
				});
				// 开始连接蓝牙
				this.connect();
			}
		},
		onHide() {
			// 页面离开前断开蓝牙连接
			this.disconnectBluetoothDevice();
		},
		methods: {
			//断开蓝牙
			disconnectBluetoothDevice() {
				// 断开蓝牙设备的逻辑
				uni.closeBLEConnection({
					deviceId: this.UUID,
					success: () => {
						console.log('蓝牙设备断开成功');
					},
					fail: (err) => {
						console.error('蓝牙设备断开失败', err);
					}
				});
			},
			//开始连接
			connect() {
				this.serviceu = getApp().globalData.mserviceuuid.toUpperCase();
				this.txdu = getApp().globalData.mtxduuid.toUpperCase();
				this.rxdu = getApp().globalData.mrxduuid.toUpperCase();
				let deviceId = this.UUID;
				console.log("开始连接蓝牙", deviceId, this.serviceu, this.txdu, this.rxdu);
				uni.getConnectedBluetoothDevices({
					services: [this.serviceu],
					success: (res) => {
						let isConnected = res.devices.some(device => device.deviceId === deviceId);
						if (isConnected) {
							console.log("设备已连接");
							this.title = "正在获取服务...";
							this.getBLEDeviceServices(deviceId);
						} else {
							this.createBLEConnection(deviceId);
						}
					},
					fail: (err) => {
						console.error("获取已连接设备失败", err);
						this.createBLEConnection(deviceId);
					}
				});
			},
			//通过id查找服务
			createBLEConnection(deviceId) {
				uni.createBLEConnection({
					deviceId,
					success: (res) => {
						console.log("连接成功", res)
						this.title = "正在获取服务...";
						this.getBLEDeviceServices(deviceId);
					},
					fail: (err) => {
						console.error("连接失败", err);
						uni.showToast({
							title: '连接失败',
							icon: 'none'
						});
					}
				});
			},
			//获取服务
			getBLEDeviceServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log("获取服务成功", res);
						let isService = res.services.some(
							(service) => this.serviceu === service.uuid
						);
						if (isService) {
							this.title = "正在获取特征值...";
							this.getBLEDeviceCharacteristics(
								deviceId,
								res.services.find((service) => this.serviceu === service.uuid).uuid
							);
						} else {
							this.title = "UUID错误";
						}
					},
					fail: (err) => {
						console.error("获取服务失败", err);
						this.title = '获取服务失败';

					}
				});
			},
			//获取特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						res.characteristics.forEach((item) => {
							if (item.properties.read) {
								uni.readBLECharacteristicValue({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
								});
							}
							if (item.properties.write && this.txdu === item.uuid) {
								this.characteristicId = item.uuid;
								this.serviceId = serviceId;
							}
							if ((item.properties.notify || item.properties.indicate) && this.rxdu ===
								item.uuid) {
								uni.notifyBLECharacteristicValueChange({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
									state: true,
									success: () => {
										uni.hideLoading();
										uni.showToast({
											title: '连接成功',
											icon: 'success'
										});
										this.listen();
									},
									fail: (err) => {
										console.error("启用通知失败", err);
										this.title = "启用通知失败";
									}
								});
							}
						});
					},
					fail: (err) => {
						console.error("获取特征值失败", err);
						this.title = '获取特征值失败';
					}
				});
			},
			//发送信号
			sendSignal(data, count) {
				// 字符串转16进制
				let uint8Array = new Uint8Array(data.length / 2);
				for (let i = 0; i < data.length; i += 2) {
					uint8Array[i / 2] = parseInt(data.substr(i, 2), 16);
				}
				let buffer = uint8Array.buffer;
				let stopSending = false; // 标志位，用于中断发送

				// 轮询发送
				const sendData = (sendCount) => {
					if (sendCount < count && !stopSending) {
						setTimeout(() => {
							uni.writeBLECharacteristicValue({
								deviceId: this.UUID,
								serviceId: this.serviceId,
								characteristicId: this.characteristicId,
								value: buffer,
								success: (res) => {
									if (this.static == "on") {
										uni.showToast({
											title: "设备已启动",
											icon: "none"
										});
									}
									stopSending = true; // 发送成功，设置标志位，中断后续发送
								},
								fail: (error) => {
									console.error("蓝牙信号发送失败", error);
									uni.showToast({
										title: "蓝牙信号发送失败",
										icon: "none"
									});
									// 根据需要添加错误处理逻辑
								},
								complete: () => {
									sendData(sendCount + 1); // 递归调用，发送下一次信号
								},
							});
						}, sendCount * 500); // 根据发送次数计算延迟时间
					}
				};

				sendData(0); // 初始化发送计数器
			},
			// 监听数据
			listen() {
				uni.onBLECharacteristicValueChange((characteristic) => {
					console.log('特征值变化:', characteristic);
					const value = characteristic.value;
					let hex = Array.prototype.map.call(new Uint8Array(value), x => ('00' + x.toString(16)).slice(-
						2)).join('');
					console.log('接收到的数据:', hex);
					this.hex = hex;
					this.uphex();
				});
			},
			//获取蓝牙信号
			getsignal() {
				return new Promise((resolve, reject) => {
					ajax("/api/meter/getcoldwaterrechargerecordBluetoothOn", "POST", {
							userId: uni.getStorageSync('userId'),
						})
						.then((data) => {
							this.signal = data.data.hex;
							console.log(this.signal);
							this.sendSignal(this.signal, 5); // 发送五次信号
							resolve();
						})
						.catch((error) => {
							console.error("请求失败:", error);
							reject(error);
						});
				});
			},
			//上传返回值
			uphex() {
				ajax("/api/meter/getcoldwaterrechargerecordBluetoothgetOn", "POST", {
						ss_mc: uni.getStorageSync('SS_MC'),
						msg: this.hex
					})
					.then((data) => {
						this.upsuccess = true
						console.log("成功上传数据:", data);
						this.data1 = data.data.getcoldwatersubsidyrecord;
					})
					.catch((error) => {
						this.upsuccess = false
						console.error("请求失败:", error);
					});
			},

			handleSearch(dateRange) {
				// 假设 dateRange 对象包含 start 和 end 属性
				this.start = dateRange.start || null; // 如果没有开始时间，则设为 null
				this.end = dateRange.end || null; // 如果没有结束时间，则设为 null

				// 重新获取数据
				this.fetchFormData();
			},
			//通过蓝牙名获取设备UUID
			getBluetoothDeviceIdByName(deviceName) {
				return new Promise((resolve, reject) => {
					// 开始蓝牙设备扫描
					uni.startBluetoothDevicesDiscovery({
						success: () => {
							// 获取蓝牙设备列表
							const getDevices = () => {
								uni.getBluetoothDevices({
									success: function(res) {
										// 遍历设备列表，寻找名称匹配的设备
										for (let i = 0; i < res.devices.length; i++) {
											if (res.devices[i].name === deviceName) {
												// 找到设备，停止扫描并返回设备ID
												uni.stopBluetoothDevicesDiscovery();
												resolve(res.devices[i].deviceId);
												return;
											}
										}
										// 如果未找到设备，继续扫描
										setTimeout(getDevices, 1000);
									},
									fail: function(err) {
										// 获取设备列表失败，返回错误信息
										uni.stopBluetoothDevicesDiscovery();
										reject(new Error('获取蓝牙设备列表失败：' + err.errMsg));
									}
								});
							};
							// 开始第一次获取设备
							getDevices();
						},
						fail: function(err) {
							// 启动设备扫描失败
							reject(new Error('启动蓝牙设备扫描失败：' + err.errMsg));
						}
					});
				});
			},


			fetchFormData() {
				let postData = {
					userId: uni.getStorageSync('userId'),
				};

				// 检查是否有时间范围，并添加到postData中
				if (this.start && this.end) {
					postData.strTime = this.start;
					postData.endTime = this.end;
				}
				ajax("/api/meter/getcoldwaterrechargerecordBluetoothOn", "POST", postData)
					.then((data) => {

						this.data1 = data.data.coldwaterrechargerecord;
						console.log("补贴数据:", data);

						// 如果没有补贴数据，提示已领取或暂无补贴
						if (this.data1.length <= 0) {
							uni.showModal({
								title: '已领取或无充值记录',
								showCancel: false, // 隐藏取消按钮
								success: (res) => {
									if (res.confirm) {
										// 用户点击确定按钮后，导航回上一页
										uni.navigateBack({
											delta: 1
										});
									}
								}
							});
						}
					})
					.catch((error) => {
						console.error("请求失败:", error);
					});
				// ajax('/api/meter/getcoldwaterrechargerecord', 'POST', postData)
				// 	.then((data) => {
				// 		console.log("成功补贴数据:", data);
				// 		this.data1 = data.data.coldwaterrechargerecord;
				// 		console.log("补贴数据有:", this.data1);
				// 	})
				// 	.catch((error) => {
				// 		console.error("请求失败:", error);
				// 	});
			},

			getStatusText(state) {
				// console.log("数据是:", this.data1.state)
				if (this.data1.length >= 1) {
					if (state == 1) {
						return "已领取";
					} else if (state == 0) {
						return "未领取";
					}
				} else {
					return "未知";
				}
			},
			convertTime(utcTimeString) {
				// 创建一个新的 Date 对象，并设置时区为UTC
				const utcDate = new Date(utcTimeString);

				// 获取本地时区与UTC之间的差异，以分钟为单位
				const offsetMinutes = utcDate.getTimezoneOffset();

				// 计算本地时间
				const localTime = new Date(utcDate.getTime() + (offsetMinutes * 60000));

				// 格式化时间
				const formattedTime = localTime.toLocaleString();

				return formattedTime;
			},
			async reback() {
				try {
					await this.getsignal(); // Wait for signal to be sent and processed
					if (this.upsuccess) {
						uni.showModal({
							title: '领取成功',
							showCancel: false, // Hide cancel button
							success: (res) => {
								if (res.confirm) {
									// Navigate back to the previous page after success
									uni.navigateBack({
										delta: 1
									});
								}
							}
						});
					} else {
						uni.showModal({
							title: '领取失败',
							showCancel: false, // Hide cancel button
						});
					}
				} catch (error) {
					console.error("Error during reback process:", error);
					uni.showModal({
						title: '领取失败',
						showCancel: false, // Hide cancel button
					});
				}
			}

		},

	};
</script>

<style scoped>
	.container {
		padding: 10px;
	}


	.title {
		font-size: 18px;
		font-weight: bold;
	}


	.table-header,
	.table-row {
		width: 200%;
		height: 50px;
		display: flex;

		align-items: center;
		border-bottom: 0.1px solid #e3e3e3;
		white-space: nowrap;
	}

	.table-cell {
		width: 50%;
		flex: 1;
		text-align: center;
		/* padding: s0px 10px; */
	}

	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px 0;
	}

	.pagination-button {
		padding: 5px 10px;
		color: black;
		border: .1px solid #e3e3e3;
		border-radius: 5px;
		cursor: pointer;
	}

	.pagination-info {
		margin: 0 10px;
	}

	.bottom-button {
		position: fixed;
		/* 按钮固定在底部 */
		bottom: 0;
		/* 按钮在底部 */
		left: 0;
		right: 0;
		background-color: #2ba245;
		color: #ffffff;
		padding: 10px;
		text-align: center;
	}
</style>